package com.example.myedittext;

import androidx.appcompat.app.AppCompatActivity;
import java.net.*;
import java.io.*;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
//import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    // 显示接收服务器消息
    private TextView receive_message0;
    private EditText ip;
    private EditText port;

    private int ListenPort = 8082;
    // 线程池
    // 为了方便展示,此处直接采用线程池进行线程管理,而没有一个个开线程
    private ExecutorService mThreadPool;

    String response;
//    public String ipString = "192.168.3.32";   // 192.168.31.71服务器端ip   10.3.183.84
//    public String port1 = "8082";  //7890服务器端口

    // 验证 IP 地址格式
    public static boolean isValidIP(String ip) {
        String ipPattern = "^192\\.168\\.(\\d{1,3})\\.(\\d{1,3})$";
        return Pattern.matches(ipPattern, ip);
    }

    // 验证端口号格式
    public static boolean isValidPort(String port) {
        try {
            int portNumber = Integer.parseInt(port);
            return portNumber >= 0 && portNumber <= 65535 && port.length() <= 5 && port.matches("\\d{4}");
        } catch (NumberFormatException e) {
            return false;
        }
    }

    private void linstenToServer() {
        runOnUiThread(() -> {
             Toast.makeText(MainActivity.this, "监听。。。"+ListenPort,
             Toast.LENGTH_SHORT).show();
        });


        System.out.println("监听。。。"+ListenPort);
//        receive_message = (TextView) findViewById(R.id.text_view0);
//        mThreadPool.execute(() -> {
//        new Thread(new Runnable() {
//        @Override
//        public void run() {
        //接收消息8082
        //不带参数的 ServerSocket服务器将绑定到一个随机可用的端口。
        // 如果你需要知道服务器实际绑定的端口号，可以使用 serverSocket.getLocalPort() 方法获取
        try (ServerSocket serverSocket = new ServerSocket(ListenPort)) {
            System.out.println("等待连接..."+ListenPort);
            runOnUiThread(() -> {
                Toast.makeText(MainActivity.this, "等待连接。。。"+ListenPort, Toast.LENGTH_SHORT).show();
            });
            try (Socket socket = serverSocket.accept()) {
                System.out.println("连接到: " + socket.getInetAddress());
// 判断客户端和服务器是否连接成功
                if (socket.isConnected()) {
                    System.out.println("连接成功");
                    runOnUiThread(() -> {
                        Toast.makeText(MainActivity.this, "socket连接成功", Toast.LENGTH_SHORT).show();
                    });
                }
//                Toast.makeText(MainActivity.this, "有人找你了", Toast.LENGTH_SHORT).show();
                System.out.println("建立连接");
            try (InputStreamReader socIn = new InputStreamReader(socket.getInputStream());

                 BufferedReader socBuf = new BufferedReader(socIn);
                 PrintWriter socOut = new PrintWriter(socket.getOutputStream(), true);
                 InputStreamReader sysIn = new InputStreamReader(System.in);
                 BufferedReader sysBuf = new BufferedReader(sysIn)) {

                System.out.println("建立输出流");
                System.out.println("socket连接成功");
                socOut.println("成功连接到: " + ListenPort);
                while (true) {
                    try {
                        String message = socBuf.readLine();
                        runOnUiThread(() -> {
                             Toast.makeText(MainActivity.this, "接收到消息"+message, Toast.LENGTH_SHORT).show();
                        });
                        if(message == null || message.isEmpty() || message.equals("null")){
                            System.out.println("客户端关闭了连接");
                            runOnUiThread(() -> {
                                Toast.makeText(MainActivity.this, "客户端关闭了连接"+message, Toast.LENGTH_SHORT).show();
                            });
                            break;
                        }

                        socOut.println("已收到消息: " + message);
                        System.out.println("收到消息: " + message);
                        // 在主线程中更新 UI
                        runOnUiThread(() -> {
//                            receive_message0.setText("收到消息: " + message);
                            receive_message0.append(message +"\n");
                        });

//                        //接收数据
//                        response = sysBuf.readLine();
//                        //接收到的显示在屏幕上
//                        receive_message.append(response +"\n");
                    } catch (SocketException e) {
                        System.err.println("连接重置: " + e.getMessage());
                        break;
                    } catch (IOException e) {
                        System.err.println("IO异常: " + e.getMessage());
                        break;
                    }
                }
                // 关闭资源
                socBuf.close();
                socket.close();
            }
                }
//            catch (Exception e) {
//                    System.err.println("Error: " + e.getMessage());
//                    e.printStackTrace();
//                }
            } catch (Exception e) {
                System.err.println("Error: " + e.getMessage());
                e.printStackTrace();
            }
//        }
//        });
//        }).start();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ip = findViewById(R.id.ip);
        System.out.println("ip是"+ip);
        port= findViewById(R.id.port);
        System.out.println("port是"+port);
        Button btn=findViewById(R.id.btn);


        receive_message0 = (TextView) findViewById(R.id.text_view0);


        // 初始化线程池
//        mThreadPool = Executors.newCachedThreadPool();
        // 初始化线程池
        mThreadPool = Executors.newCachedThreadPool();

        // 在后台线程中执行监听服务器消息的方法
        mThreadPool.execute(this::linstenToServer);
//        linstenToServer();

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String iptext = ip.getText().toString();//获取ip内容
                String porttext = port.getText().toString();;//获取port内容
                if(iptext.isEmpty() && porttext.isEmpty()){
                    Toast.makeText(MainActivity.this, "请输入ip地址和端口号", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(iptext.isEmpty()){
                    Toast.makeText(MainActivity.this, "请输入ip地址", Toast.LENGTH_SHORT).show();
                    System.out.println("请输入ip");
                    return;
                }
                if(porttext.isEmpty()){
                    Toast.makeText(MainActivity.this, "请输入端口号", Toast.LENGTH_SHORT).show();
                    System.out.println("请输入端口号");
                    return;
                }
//                if (iptext.equals(ipString)&&porttext.equals(port1))
                if (isValidIP(iptext)) {
                    if(isValidPort(porttext)){
                      Intent intent = new Intent();  //进入第二页
                      intent.putExtra("IP", iptext);
                      intent.putExtra("PORT", porttext);
                      intent.setClass(MainActivity.this,MainActivity2.class);
                        startActivity(intent);
                    }else {
                        Toast.makeText(MainActivity.this, "端口号格式错误", Toast.LENGTH_SHORT).show();
                        System.out.println("端口格式错误");
                    }
                } else {
                    Toast.makeText(MainActivity.this, "IP格式错误", Toast.LENGTH_SHORT).show();
                    System.out.println("IP格式错误");
                }
            }
        });
//        }).start();
    }
}


